package no.ntnu.fp.handlers;

import java.io.IOException;
import java.util.List;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.MeetingsForEmployeeMessage;
import no.ntnu.fp.messages.impl.RequestMeetingsForEmployeeMessage;
import no.ntnu.fp.messages.impl.RequestMeetingsForEmployeeMessage;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.MeetingService;

public class RequestMeetingsForEmployeeHandler implements Handler {
	private final MeetingService meetingService;
	
	public RequestMeetingsForEmployeeHandler(
			MeetingService meetingService) {
		this.meetingService = meetingService;
	}

	@Override
	public void handleMessage(Message message) {
		RequestMeetingsForEmployeeMessage request = 
			(RequestMeetingsForEmployeeMessage) message;
		
		Employee employee = request.getEmployee();
		
		List<Meeting> meetings
				= meetingService.getMeetingsByEmployee(employee);
		
		MeetingsForEmployeeMessage reply 
				= new MeetingsForEmployeeMessage(employee, meetings);
		
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException(
					"Could not send meetings for employee " + employee, e);
		}
		
	}

}
